<?php

require_once 'include.php';

use sdk\Image;
use sdk\WeiXin;
use sdk\Db;

define('HYURL', 'http://wx.hui-dian.cn');

$cwx = new WeiXin($customerAppName, $customerAppId, $customerAppSecret);
$swx = new WeiXin($serverAppName, $serverAppId, $serverAppSecret);
$db = new Db($host, $username, $passwd, $schema);

################################################################################
// 以下方法在提交公众号服务器配置信息时被调用
//$swx->valid();
################################################################################
// 检查微信认证签名
if (!$swx->checkSignature()) {
    throw new Exception('Invalid Credential');
}

// 检查输入数据
if (empty($GLOBALS["HTTP_RAW_POST_DATA"])) {
    throw new Exception('Empty Post');
}

try {
    // 获得输入数据
    $postStr = $GLOBALS["HTTP_RAW_POST_DATA"];

    // 读取XML请求。出于安全角度考虑，防止外部注入
    libxml_disable_entity_loader(true);
    $post_object = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);

    $server_openid = "$post_object->FromUserName";
    $developer_wxid = "$post_object->ToUserName";

    // 从微信公众号获取商户信息
    $profile = $swx->getProfile($server_openid);
    $nickname = $profile->nickname;

    // 保存商户信息到慧店数据库
    if ($db->getServerId($server_openid) == null) {
        $db->saveServer($profile);
    }
    // 在之后的操作中均使用慧店id，而不是微信提供的openid
    $server_id = $db->getServerId($server_openid);

    $message_type = "$post_object->MsgType";
    switch ($message_type) {
        // 收到事件推送消息
        case 'event':
            $event = "$post_object->Event";
            $event_key = "$post_object->EventKey";

            switch ($event) {
                // 商户关注公众号
                case 'subscribe':
                    $shop_id = substr($event_key, 8, -1);
                    $role = substr($event_key, -1);

                    $db->followShop($server_id, $shop_id, $role);
                    $db->setServerCurrentShop($shop_id, $server_id);

                    $content_response = $nickname . '，欢迎关注"美美盟"公众号，<a href="' . HYURL .
                            '/shop.php?shop_id=' . $shop_id .
                            '">点此进入您的店铺</a>';

                    $swx->responseTextXML($server_openid, $developer_wxid, $content_response);
                    break;

                // 商户点击菜单反馈项
                case 'CLICK':
                    // 权限检查，只有店主和店员可以接单、结单
                    $server_role = $db->getServerRole($server_id);
                    if ($server_role == 0 || $server_role == 1) {
                        switch ($event_key) {
                            case 'start_service':
                                $service_id = $db->getLatestServiceId($server_id);
                                if (!$db->isServiceEnded($service_id)) {
                                    $content_response = "请先为美单号为{$service_id}的服务结单。";
                                    $swx->responseTextXML($server_openid, $developer_wxid, $content_response);
                                } else {
                                    $db->startService($server_id);
                                    $service_id = $db->getLatestServiceId($server_id);
                                    $swx->startServiceNotification($server_openid, 1.5, 100, $service_id);
                                    echo 'success';
                                    break;
                                }
                                break;
                            case 'end_service':
                                // 从最近的一单开始结单
                                $service_id = $db->getLatestServiceId($server_id);
                                if (!$db->isServiceEnded($service_id)) {
                                    $db->endService($service_id);
                                }
                                $content_response = "美单号为{$service_id}的服务成功结单，别忘了晒单噢。";
                                $swx->responseTextXML($server_openid, $developer_wxid, $content_response);
                                break;
                            default :
                                throw new Exception('欢迎关注美美盟！');
                        }
                    } else {
                        $content_response = '请与店主联系，获取相关权限';
                        $swx->responseTextXML($server_openid, $developer_wxid, $content_response);
                    }
                    
                    break;

                // 商户点击菜单跳转项
                case 'VIEW':
                    $content_response = $event_key;
                    $swx->responseTextXML($server_openid, $developer_wxid, $content_response);
                    break;

                // 商户取消关注公众号
                case 'unsubscribe':
                    $content_request = '感谢所有一起度过的时光';
                    $swx->responseTextXML($server_openid, $developer_wxid, $content_response);
                    break;

                // 商户扫描二维码
                case 'SCAN':
                    $shop_id = substr($event_key, 0, -1);
                    $role = substr($event_key, -1);

                    $db->followShop($server_id, $shop_id, $role);
                    $db->setServerCurrentShop($shop_id, $server_id);

                    $content_response = $nickname . '，欢迎关注"美美盟"公众号，<a href="' . HYURL .
                            '/shop.php?shop_id=' . $shop_id .
                            '">点此进入您的店铺</a>';

                    $swx->responseTextXML($server_openid, $developer_wxid, $content_response);
                    break;

                // 商户新建门店 
                case 'poi_check_notify':
                    $poi_id = "$post_object->PoiId";
                    $content_response = $poi_id;
                    $swx->responseTextXML($server_openid, $developer_wxid, $content_response);

                default :
                    throw new Exception('欢迎关注美美盟！');
            }
            break;


        // 收到客户文本消息
        case 'text':
            $content_request = trim($post_object->Content);

            $content_response = $content_request;
            $swx->responseTextXML($server_openid, $developer_wxid, $content_response);
            break;

        // 收到客户图像消息
        case 'image':
            // 从最近的一单开始更新图片
            $service_id = $db->getLatestServiceId($server_id);
            // 只有当最近的一单已经结束才能开始晒单
            if ($db->isServiceEnded($service_id)) {
                $media_id = "$post_object->MediaId";
                $image_full_name = $swx->saveMediaFile($media_id);

                // 将二维码文件上传到万象图片
                $uploadRet = Image::upload($image_full_name);

                // 删除服务器端文件
                unlink($image_full_name);

                if (0 === $uploadRet['code']) {
                    // 获取万象图片分配的fileid
                    $fileid = $uploadRet['data']['fileid'];
                    $db->updateServiceImage($service_id, $fileid);

                    // 生成包含本service_id的用户平台二维码
                    $role = 9; // 当role为9时，scene_id的前半部分为service_id
                    $scene_id = $service_id . $role;
                    $json_str = '{"expire_seconds": 3600, "action_name": "QR_SCENE", 
                            "action_info": {"scene": {"scene_id": ' . $scene_id . '}}}';
                    $qrcode_url = $cwx->createQRcodeUrl($json_str);

                    $image_full_name = $cwx->saveRemoteFile($qrcode_url);
                    $media_id = $swx->uploadMediaFile($image_full_name);
                    unlink($image_full_name);

                    $swx->responseImageXML($server_openid, $developer_wxid, $media_id);
                } else {
                    $content_response = "很抱歉，系统正忙，请重试。";
                    $swx->responseTextXML($server_openid, $developer_wxid, $content_response);
                }
            } else {
                $content_response = "请先为美单号为{$service_id}的工单结单";
                $swx->responseTextXML($server_openid, $developer_wxid, $content_response);
            }


            break;

        // 收到客户语音消息
        case 'voice':
            break;

        // 收到客户视频消息
        case 'video':
            $media_id = "$post_object->MediaId";
            $content_response = $media_id;
            $swx->responseTextXML($server_openid, $developer_wxid, $content_response);
            break;

        default:
            throw new Exception('Unknown Message Type');
    }
} catch (Exception $e) {
    $swx->responseTextXML($server_openid, $developer_wxid, $e->getMessage());
}

